<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>代理管理</title>
    <link href="../css/bootstrap.min.css" rel="stylesheet">
    <link href="../css/bootstrap-icons.css" rel="stylesheet">
    <style>
        .sidebar {
            min-height: 100vh;
            background-color: #f8f9fa;
        }
        .main-content {
            padding: 20px;
        }
        .card {
            margin-bottom: 20px;
        }
        .btn-group-sm .btn {
            padding: 0.25rem 0.5rem;
            font-size: 0.875rem;
        }
        .status-badge {
            font-size: 0.75rem;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <div class="col-md-3 col-lg-2 sidebar p-3">
                <h4 class="mb-4">代理管理</h4>
                <div class="list-group mb-3">
                    <a href="#" class="list-group-item list-group-item-action active" onclick="showGroups()">
                        <i class="bi bi-collection"></i> 分组管理
                    </a>
                    <a href="#" class="list-group-item list-group-item-action" onclick="showProxies()">
                        <i class="bi bi-arrow-left-right"></i> 代理配置
                    </a>
                </div>
                
                <!-- 代理配置筛选 -->
                <div id="proxy-filters" style="display: none;">
                    <div class="mb-3">
                        <button class="btn btn-primary w-100" onclick="showCreateProxyModal()">
                            <i class="bi bi-plus-circle"></i> 新增代理
                        </button>
                    </div>
                    <div class="mb-3">
                        <input type="text" class="form-control" id="searchInput" placeholder="搜索代理..." onkeyup="filterProxies()">
                    </div>
                    <div class="mb-3">
                        <select class="form-select" id="groupFilter" onchange="filterProxies()">
                            <option value="">所有分组</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <select class="form-select" id="statusFilter" onchange="filterProxies()">
                            <option value="">所有状态</option>
                            <option value="true">启用</option>
                            <option value="false">禁用</option>
                        </select>
                    </div>
                </div>
            </div>

            <!-- 主内容区 -->
            <div class="col-md-9 col-lg-10 main-content">
                <!-- 分组管理 -->
                <div id="groups-section">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h2>代理分组管理</h2>
                        <div>
                            <button class="btn btn-primary" onclick="showAddGroupModal()">
                                <i class="bi bi-plus"></i> 新增分组
                            </button>
                        </div>
                    </div>
                    <div id="groups-list">
                        <!-- 分组列表将在这里动态加载 -->
                    </div>
                </div>

                <!-- 代理配置管理 -->
                <div id="proxies-section" style="display: none;">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h2>代理配置列表</h2>
                        <div>
                            <button class="btn btn-outline-secondary" onclick="refreshProxyList()">
                                <i class="bi bi-arrow-clockwise"></i> 刷新
                            </button>
                        </div>
                    </div>
                    <div id="proxyList">
                        <!-- 代理列表将在这里动态加载 -->
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 新增/编辑分组模态框 -->
    <div class="modal fade" id="groupModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="groupModalTitle">新增代理分组</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="groupForm">
                        <input type="hidden" id="groupId">
                        <div class="mb-3">
                            <label for="groupName" class="form-label">分组名称 *</label>
                            <input type="text" class="form-control" id="groupName" required>
                        </div>
                        <div class="mb-3">
                            <label for="groupDescription" class="form-label">描述</label>
                            <textarea class="form-control" id="groupDescription" rows="3"></textarea>
                        </div>
                        <div class="mb-3">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="groupEnabled" checked>
                                <label class="form-check-label" for="groupEnabled">
                                    启用分组
                                </label>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="saveGroup()">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 新增/编辑代理模态框 -->
    <div class="modal fade" id="proxyModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="proxyModalTitle">新增代理配置</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="proxyForm">
                        <input type="hidden" id="proxyId">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="proxyName" class="form-label">代理名称 *</label>
                                <input type="text" class="form-control" id="proxyName" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="proxyGroup" class="form-label">所属分组</label>
                                <select class="form-select" id="proxyGroup">
                                    <option value="">选择分组</option>
                                </select>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label for="proxyDescription" class="form-label">描述</label>
                            <textarea class="form-control" id="proxyDescription" rows="2"></textarea>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="sourcePath" class="form-label">源路径 *</label>
                                <input type="text" class="form-control" id="sourcePath" placeholder="/api/example" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="targetUrl" class="form-label">目标URL *</label>
                                <input type="text" class="form-control" id="targetUrl" placeholder="http://target-service:8080/api" required>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label for="proxyMethod" class="form-label">HTTP方法 *</label>
                                <select class="form-select" id="proxyMethod" required>
                                    <option value="GET">GET</option>
                                    <option value="POST">POST</option>
                                    <option value="PUT">PUT</option>
                                    <option value="DELETE">DELETE</option>
                                    <option value="PATCH">PATCH</option>
                                </select>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label for="timeout" class="form-label">超时时间(ms)</label>
                                <input type="number" class="form-control" id="timeout" value="5000" min="1000" max="60000">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label for="retryCount" class="form-label">重试次数</label>
                                <input type="number" class="form-control" id="retryCount" value="0" min="0" max="10">
                            </div>
                        </div>
                        <div class="mb-3">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="proxyEnabled" checked>
                                <label class="form-check-label" for="proxyEnabled">
                                    启用代理
                                </label>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="saveProxy()">保存</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 获取当前页面的上下文路径（去掉最后的 /index.html 或 /）
        const getCurrentContextPath = () => {
            const path = window.location.pathname;
            // 如果路径是 /svr/ 或 /svr/index.html，返回 /svr
            const pathParts = path.split('/').filter(p => p);
            if (pathParts.length === 0) return '';
            if (pathParts[0] === 'proxyPage')
                return '';
            else return '/' + pathParts[0]; // 返回 /svr
        };

        const APP_CONTEXT_PATH = getCurrentContextPath();
    </script>
    <script src="../js/bootstrap.bundle.min.js"></script>
    <script>
        let proxyList = [];
        let groupList = [];
        let proxyModal;
        let groupModal;

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            proxyModal = new bootstrap.Modal(document.getElementById('proxyModal'));
            groupModal = new bootstrap.Modal(document.getElementById('groupModal'));
            loadGroups();
            loadProxyList();
        });

        // 显示分组管理
        function showGroups() {
            document.getElementById('groups-section').style.display = 'block';
            document.getElementById('proxies-section').style.display = 'none';
            document.getElementById('proxy-filters').style.display = 'none';
            document.querySelectorAll('.list-group-item').forEach(item => item.classList.remove('active'));
            event.target.classList.add('active');
        }

        // 显示代理配置
        function showProxies() {
            document.getElementById('groups-section').style.display = 'none';
            document.getElementById('proxies-section').style.display = 'block';
            document.getElementById('proxy-filters').style.display = 'block';
            document.querySelectorAll('.list-group-item').forEach(item => item.classList.remove('active'));
            event.target.classList.add('active');
        }

        // 加载分组列表
        async function loadGroups() {
            try {
                const response = await fetch(`${APP_CONTEXT_PATH}/proxy/group/list`);
                const result = await response.json();
                if (result.success) {
                    groupList = result.data;
                    renderGroups();
                    updateGroupOptions();
                }
            } catch (error) {
                console.error('加载分组失败:', error);
            }
        }

        // 渲染分组列表
        function renderGroups() {
            const container = document.getElementById('groups-list');
            if (groupList.length === 0) {
                container.innerHTML = '<div class="alert alert-info">暂无分组数据</div>';
                return;
            }

            const html = groupList.map(group => `
                <div class="card">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h5 class="card-title">${group.name}</h5>
                                <p class="card-text text-muted">${group.description || '暂无描述'}</p>
                                <small class="text-muted">状态: ${group.enabled ? '启用' : '禁用'}</small>
                            </div>
                            <div class="btn-group btn-group-sm">
                                <button class="btn btn-outline-primary" onclick="editGroup(${group.id})">
                                    <i class="bi bi-pencil"></i>
                                </button>
                                <button class="btn btn-outline-danger" onclick="deleteGroup(${group.id})">
                                    <i class="bi bi-trash"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            `).join('');

            container.innerHTML = html;
        }

        // 更新分组选项
        function updateGroupOptions() {
            const groupFilter = document.getElementById('groupFilter');
            const proxyGroup = document.getElementById('proxyGroup');
            
            // 清空现有选项
            groupFilter.innerHTML = '<option value="">所有分组</option>';
            proxyGroup.innerHTML = '<option value="">选择分组</option>';
            
            // 添加分组选项
            groupList.forEach(group => {
                groupFilter.innerHTML += `<option value="${group.id}">${group.name}</option>`;
                proxyGroup.innerHTML += `<option value="${group.id}">${group.name}</option>`;
            });
        }

        // 显示新增分组模态框
        function showAddGroupModal() {
            document.getElementById('groupModalTitle').textContent = '新增代理分组';
            document.getElementById('groupForm').reset();
            document.getElementById('groupId').value = '';
            groupModal.show();
        }

        // 编辑分组
        function editGroup(id) {
            const group = groupList.find(g => g.id === id);
            if (group) {
                document.getElementById('groupModalTitle').textContent = '编辑代理分组';
                document.getElementById('groupId').value = group.id;
                document.getElementById('groupName').value = group.name;
                document.getElementById('groupDescription').value = group.description || '';
                document.getElementById('groupEnabled').checked = group.enabled;
                groupModal.show();
            }
        }

        // 保存分组
        async function saveGroup() {
            const form = document.getElementById('groupForm');
            if (!form.checkValidity()) {
                form.reportValidity();
                return;
            }

            const groupData = {
                id: document.getElementById('groupId').value || null,
                name: document.getElementById('groupName').value,
                description: document.getElementById('groupDescription').value,
                enabled: document.getElementById('groupEnabled').checked
            };

            try {
                const url = groupData.id ? `${APP_CONTEXT_PATH}/proxy/group/update` : `${APP_CONTEXT_PATH}/proxy/group/create`;
                const method = groupData.id ? 'PUT' : 'POST';

                const response = await fetch(url, {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(groupData)
                });

                const result = await response.json();
                if (result.success) {
                    groupModal.hide();
                    loadGroups();
                    alert(result.message);
                } else {
                    alert('保存失败: ' + result.message);
                }
            } catch (error) {
                console.error('保存分组失败:', error);
                alert('保存失败: ' + error.message);
            }
        }

        // 删除分组
        async function deleteGroup(id) {
            if (!confirm('确定要删除这个分组吗？')) {
                return;
            }

            try {
                const response = await fetch(`${APP_CONTEXT_PATH}/proxy/group/${id}`, {
                    method: 'DELETE'
                });
                const result = await response.json();
                if (result.success) {
                    loadGroups();
                    alert(result.message);
                } else {
                    alert('删除失败: ' + result.message);
                }
            } catch (error) {
                console.error('删除分组失败:', error);
                alert('删除失败: ' + error.message);
            }
        }

        // 加载代理列表
        async function loadProxyList() {
            try {
                const response = await fetch(`${APP_CONTEXT_PATH}/proxy/config/list`);
                const result = await response.json();
                if (result.success) {
                    proxyList = result.data;
                    renderProxyList();
                }
            } catch (error) {
                console.error('加载代理列表失败:', error);
            }
        }

        // 渲染代理列表
        function renderProxyList() {
            const container = document.getElementById('proxyList');
            if (proxyList.length === 0) {
                container.innerHTML = '<div class="alert alert-info">暂无代理配置</div>';
                return;
            }

            let html = '';
            proxyList.forEach(proxy => {
                const group = groupList.find(g => g.id === proxy.groupId);
                const groupName = group ? group.name : '未分组';
                const statusClass = proxy.enabled ? 'success' : 'secondary';
                const statusText = proxy.enabled ? '启用' : '禁用';

                html += `
                    <div class="card proxy-item" data-id="${proxy.id}" data-group="${proxy.groupId}" data-enabled="${proxy.enabled}">
                        <div class="card-body">
                            <div class="row align-items-center">
                                <div class="col-md-8">
                                    <div class="d-flex align-items-center mb-2">
                                        <h5 class="card-title mb-0 me-3">${proxy.name}</h5>
                                        <span class="badge bg-${statusClass} status-badge">${statusText}</span>
                                        <span class="badge bg-info status-badge ms-1">${groupName}</span>
                                    </div>
                                    <p class="card-text text-muted mb-2">${proxy.description || '暂无描述'}</p>
                                    <div class="row">
                                        <div class="col-md-6">
                                            <small class="text-muted">
                                                <strong>源路径:</strong> ${proxy.sourcePath}
                                            </small>
                                        </div>
                                        <div class="col-md-6">
                                            <small class="text-muted">
                                                <strong>目标URL:</strong> ${proxy.targetUrl}
                                            </small>
                                        </div>
                                    </div>
                                    <div class="row mt-1">
                                        <div class="col-md-4">
                                            <small class="text-muted">
                                                <strong>方法:</strong> ${proxy.method}
                                            </small>
                                        </div>
                                        <div class="col-md-4">
                                            <small class="text-muted">
                                                <strong>超时:</strong> ${proxy.timeout}ms
                                            </small>
                                        </div>
                                        <div class="col-md-4">
                                            <small class="text-muted">
                                                <strong>重试:</strong> ${proxy.retryCount}次
                                            </small>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-4 text-end">
                                    <div class="btn-group btn-group-sm">
                                        <button class="btn btn-outline-primary" onclick="editProxy(${proxy.id})">
                                            <i class="bi bi-pencil"></i>
                                        </button>
                                        <button class="btn btn-outline-${proxy.enabled ? 'warning' : 'success'}" onclick="toggleProxyStatus(${proxy.id})">
                                            <i class="bi bi-${proxy.enabled ? 'pause' : 'play'}"></i>
                                        </button>
                                        <button class="btn btn-outline-danger" onclick="deleteProxy(${proxy.id})">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
            });
            container.innerHTML = html;
        }

        // 过滤代理列表
        function filterProxies() {
            const searchTerm = document.getElementById('searchInput').value.toLowerCase();
            const groupFilter = document.getElementById('groupFilter').value;
            const statusFilter = document.getElementById('statusFilter').value;

            const items = document.querySelectorAll('.proxy-item');
            items.forEach(item => {
                const name = item.querySelector('.card-title').textContent.toLowerCase();
                const description = item.querySelector('.card-text').textContent.toLowerCase();
                const group = item.getAttribute('data-group');
                const enabled = item.getAttribute('data-enabled');

                const matchesSearch = name.includes(searchTerm) || description.includes(searchTerm);
                const matchesGroup = !groupFilter || group === groupFilter;
                const matchesStatus = !statusFilter || enabled === statusFilter;

                if (matchesSearch && matchesGroup && matchesStatus) {
                    item.style.display = 'block';
                } else {
                    item.style.display = 'none';
                }
            });
        }

        // 显示新增代理模态框
        function showCreateProxyModal() {
            document.getElementById('proxyModalTitle').textContent = '新增代理配置';
            document.getElementById('proxyForm').reset();
            document.getElementById('proxyId').value = '';
            proxyModal.show();
        }

        // 编辑代理
        async function editProxy(id) {
            try {
                const response = await fetch(`${APP_CONTEXT_PATH}/proxy/config/${id}`);
                const result = await response.json();
                if (result.success) {
                    const proxy = result.data;
                    fillProxyForm(proxy);
                    document.getElementById('proxyModalTitle').textContent = '编辑代理配置';
                    proxyModal.show();
                }
            } catch (error) {
                console.error('获取代理详情失败:', error);
            }
        }

        // 填充代理表单
        function fillProxyForm(proxy) {
            document.getElementById('proxyId').value = proxy.id;
            document.getElementById('proxyName').value = proxy.name;
            document.getElementById('proxyDescription').value = proxy.description || '';
            document.getElementById('sourcePath').value = proxy.sourcePath;
            document.getElementById('targetUrl').value = proxy.targetUrl;
            document.getElementById('proxyMethod').value = proxy.method;
            document.getElementById('timeout').value = proxy.timeout;
            document.getElementById('retryCount').value = proxy.retryCount;
            document.getElementById('proxyGroup').value = proxy.groupId || '';
            document.getElementById('proxyEnabled').checked = proxy.enabled;
        }

        // 保存代理
        async function saveProxy() {
            const form = document.getElementById('proxyForm');
            if (!form.checkValidity()) {
                form.reportValidity();
                return;
            }

            const proxyData = {
                id: document.getElementById('proxyId').value || null,
                name: document.getElementById('proxyName').value,
                description: document.getElementById('proxyDescription').value,
                sourcePath: document.getElementById('sourcePath').value,
                targetUrl: document.getElementById('targetUrl').value,
                method: document.getElementById('proxyMethod').value,
                timeout: parseInt(document.getElementById('timeout').value),
                retryCount: parseInt(document.getElementById('retryCount').value),
                groupId: document.getElementById('proxyGroup').value || null,
                enabled: document.getElementById('proxyEnabled').checked
            };

            try {
                const url = proxyData.id ? `${APP_CONTEXT_PATH}/proxy/config/update` : `${APP_CONTEXT_PATH}/proxy/config/create`;
                const method = proxyData.id ? 'PUT' : 'POST';

                const response = await fetch(url, {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(proxyData)
                });

                const result = await response.json();
                if (result.success) {
                    proxyModal.hide();
                    loadProxyList();
                    alert(result.message);
                } else {
                    alert('保存失败: ' + result.message);
                }
            } catch (error) {
                console.error('保存代理失败:', error);
                alert('保存失败: ' + error.message);
            }
        }

        // 切换代理状态
        async function toggleProxyStatus(id) {
            if (!confirm('确定要切换代理状态吗？')) {
                return;
            }

            try {
                const response = await fetch(`${APP_CONTEXT_PATH}/proxy/config/${id}/toggle`, {
                    method: 'POST'
                });
                const result = await response.json();
                if (result.success) {
                    loadProxyList();
                    alert(result.message);
                } else {
                    alert('操作失败: ' + result.message);
                }
            } catch (error) {
                console.error('切换代理状态失败:', error);
                alert('操作失败: ' + error.message);
            }
        }

        // 删除代理
        async function deleteProxy(id) {
            if (!confirm('确定要删除这个代理配置吗？')) {
                return;
            }

            try {
                const response = await fetch(`${APP_CONTEXT_PATH}/proxy/config/${id}`, {
                    method: 'DELETE'
                });
                const result = await response.json();
                if (result.success) {
                    loadProxyList();
                    alert(result.message);
                } else {
                    alert('删除失败: ' + result.message);
                }
            } catch (error) {
                console.error('删除代理失败:', error);
                alert('删除失败: ' + error.message);
            }
        }

        // 刷新代理列表
        function refreshProxyList() {
            loadProxyList();
        }
    </script>
</body>
</html>
